// 处理菜单类弹框
import { toRefs,reactive,onMounted,watchEffect, onUnmounted,provide } from 'vue'

export default function (){
    let visible = reactive({
        dateVisible:false,
        leftmenuVisible:false,
        homemenuVisible:false,
        controlmenuVisible:false
    })

    
    let iconMenu = reactive({
        visible:false,
        top:0,
        left:0,
        appData:{}
    })

    let desktopMenu = reactive({
        visible:false,
        top:0,
        left:0,
        filePath:'application'//默认路径是application
    })

    let fileMenu = reactive({
        visible:false,
        top:0,
        left:0,
        filePath:''
    })

    function openMenu(arg){
        iconMenu.visible = false
        desktopMenu.visible = false
        visible[arg]=!visible[arg]
        for(let key in visible){
            if(key!==arg){
                visible[key] = false
            }
        }
    }

    function openIconMenu(e,item){
        e.preventDefault();
        iconMenu.appData = item
        iconMenu.left = e.pageX
        iconMenu.top = e.pageY
        closeMenu()
        iconMenu.visible = true
    }

    function openDesktopMenu(e){
        e.preventDefault();
        desktopMenu.left = e.pageX
        desktopMenu.top = e.pageY
        closeMenu()
        desktopMenu.visible = true
    }

    function openFileMenu(e,path){
        e.preventDefault();
        fileMenu.left = e.pageX
        fileMenu.top = e.pageY
        closeMenu()
        fileMenu.visible = true
        fileMenu.filePath = path
    }
    
    function closeMenu() {
        iconMenu.visible = false
        desktopMenu.visible = false
        fileMenu.visible = false
        for(let key in visible){
            visible[key] = false
        }
        console.log(iconMenu.visible);
    }

    watchEffect(()=>{
        const arr = [iconMenu.visible,desktopMenu.visible,fileMenu.visible]
        for(let key in visible){
            arr.push(visible[key])
        }
        if (arr.includes(true)) {
           document.body.addEventListener('click', closeMenu)
        } else {
           document.body.removeEventListener('click', closeMenu)
        }
    })

    // provide('fileMenu',openFileMenu)
    // provide('AppMenu',openIconMenu)
    onMounted(() => {
        document.getElementById('work').addEventListener('contextmenu',openDesktopMenu)
    })

    onUnmounted(() => {
        document.getElementById('work').removeEventListener('contextmenu',openDesktopMenu)
    })


    return {
        iconMenu,
        desktopMenu,
        fileMenu,
        ...toRefs(visible),
        openMenu,
        openDesktopMenu,
        openFileMenu,
        openIconMenu,
        closeMenu,
    }

}